package com.yzd.learnjava.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import com.yzd.learnjava.util.Print;

public class CaptureUncaughtException {
	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());
		exec.execute(new ExceptionThread2());
	}
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
	public void uncaughtException(Thread t , Throwable e) {
		Print.print("caught : " + e);
	}
}

class ExceptionThread2 implements Runnable{
	public void run() {
		Thread t = Thread.currentThread();
		Print.print("run() by " + t);
		Print.print("eh = " + t.getUncaughtExceptionHandler());
		throw new RuntimeException();
	}
}

class HandlerThreadFactory implements ThreadFactory{
	public Thread newThread(Runnable r) {
		Print.print(this + " creating new Thread");
		Thread t = new Thread(r);
		Print.print("created " + t);
		t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
		Print.print("eh = " + t.getUncaughtExceptionHandler());
		return t;
	}
}
